/*
 * Copyright (c) 2025 CAX Conversion Project
 */
package com.comac.ins.isfd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.comac.ins.common.core.domain.model.LoginUser;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.MapstructUtils;
import com.comac.ins.common.core.utils.StringUtils;
import com.comac.ins.common.mybatis.core.page.PageQuery;
import com.comac.ins.common.mybatis.core.page.TableDataInfo;
import com.comac.ins.common.satoken.utils.LoginHelper;
import com.comac.ins.isfd.domain.IsfdMetadataDatabase;
import com.comac.ins.isfd.domain.IsfdMetadataManagement;
import com.comac.ins.isfd.domain.bo.IsfdMetadataDatabaseBo;
import com.comac.ins.isfd.domain.vo.IsfdMetadataDatabaseVo;
import com.comac.ins.isfd.mapper.IsfdMetadataDatabaseMapper;
import com.comac.ins.isfd.mapper.IsfdMetadataManagementMapper;
import com.comac.ins.isfd.service.IIsfdMetadataDatabaseService;
import com.comac.ins.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 元数据管理-要素库Service业务层处理
 *
 * @author Lion Li
 * @date 2024-09-23
 */
@RequiredArgsConstructor
@Service
public class IsfdMetadataDatabaseServiceImpl implements IIsfdMetadataDatabaseService {

    @Autowired
    private IsfdMetadataDatabaseMapper baseMapper;

    @Autowired
    private IsfdMetadataManagementMapper isfdMetadataManagementMapper;
    private final SysUserMapper userMapper;

    /**
     * 查询元数据管理-要素库
     *
     * @param id 主键
     * @return 元数据管理-要素库
     */
    @Override
    public IsfdMetadataDatabaseVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询元数据管理-要素库列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 元数据管理-要素库分页列表
     */
    @Override
    public TableDataInfo<IsfdMetadataDatabaseVo> queryPageList(IsfdMetadataDatabaseBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<IsfdMetadataDatabase> lqw = buildQueryWrapper(bo);
        lqw.eq(IsfdMetadataDatabase::getIsDeleted, 0);
        pageQuery.setOrderByColumn("create_time");
        Page<IsfdMetadataDatabaseVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);


        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的元数据管理-要素库列表
     *
     * @param bo 查询条件
     * @return 元数据管理-要素库列表
     */
    @Override
    public TableDataInfo<IsfdMetadataDatabaseVo> queryList(IsfdMetadataDatabaseBo bo, PageQuery pageQuery) {
//        LambdaQueryWrapper<IsfdMetadataDatabase> lqw = buildQueryWrapper(bo);
//        lqw.eq(IsfdMetadataDatabase::getIsDeleted,  0);
        QueryWrapper<IsfdMetadataDatabase> queryWrapper = new QueryWrapper<>();
        String databaseType = bo.getDatabaseType();
        Long sceneId = bo.getSceneId();
        if (databaseType != null) {
            queryWrapper.eq("database_type", databaseType);
        }
        if (sceneId != null) {
            queryWrapper.inSql("id", "SELECT database_id FROM isfd_metadata_business_ref_database WHERE business_id = " + sceneId);
        }
        queryWrapper.eq("is_deleted", 0);
        Page<IsfdMetadataDatabaseVo> result = baseMapper.selectVoPage(pageQuery.build(), queryWrapper);
        return TableDataInfo.build(result);
    }

    private LambdaQueryWrapper<IsfdMetadataDatabase> buildQueryWrapper(IsfdMetadataDatabaseBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<IsfdMetadataDatabase> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), IsfdMetadataDatabase::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getDatabaseType()), IsfdMetadataDatabase::getDatabaseType, bo.getDatabaseType());
        lqw.like(StringUtils.isNotBlank(bo.getCreateByName()), IsfdMetadataDatabase::getCreateByName, bo.getCreateByName());
        lqw.eq(StringUtils.isNotBlank(bo.getDatabaseSchema()), IsfdMetadataDatabase::getDatabaseSchema, bo.getDatabaseSchema());
        lqw.eq(StringUtils.isNotBlank(bo.getPermissions()), IsfdMetadataDatabase::getPermissions, bo.getPermissions());
        lqw.eq(StringUtils.isNotBlank(bo.getStorageLocation()), IsfdMetadataDatabase::getStorageLocation, bo.getStorageLocation());
        lqw.eq(bo.getIsDeleted() != null, IsfdMetadataDatabase::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增元数据管理-要素库
     *
     * @param bo 元数据管理-要素库
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(IsfdMetadataDatabaseBo bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        bo.setCreateByName(loginUser.getUsername());
        IsfdMetadataDatabase add = MapstructUtils.convert(bo, IsfdMetadataDatabase.class);
        boolean flag = baseMapper.insert(add) > 0;
        return flag;
    }

    /**
     * 修改元数据管理-要素库
     *
     * @param bo 元数据管理-要素库
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(IsfdMetadataDatabaseBo bo) {
        IsfdMetadataDatabase update = MapstructUtils.convert(bo, IsfdMetadataDatabase.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(IsfdMetadataDatabase entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除元数据管理-要素库信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids) {
        for (Long databaseId : ids) {
            List<IsfdMetadataManagement> isfdMetadataManagementList = isfdMetadataManagementMapper.selectList(new LambdaQueryWrapper<IsfdMetadataManagement>()
                .eq(IsfdMetadataManagement::getDatabaseId, databaseId));
            if (CollectionUtils.isNotEmpty(isfdMetadataManagementList)) {
                IsfdMetadataManagement isfdMetadataManagement = isfdMetadataManagementList.get(0);
                throw new BaseException("id为：" + databaseId + "的要素数据库不能删除，该要素数据库已经导入过业务：" + isfdMetadataManagement.getBusinessName() + "的数据");
            }
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
